from flask import Flask, request, jsonify
from flask_cors import CORS
import json
import datetime
import os
from zhipuai import ZhipuAI
from pathlib import Path
from openai import OpenAI
from spire.xls import *
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders


app = Flask(__name__)
CORS(app)  # 允许所有源的 CORS

@app.route('/metting_star', methods=['POST'])


def post_data():
    
    # print('dfd')
    
    # 获取原始数据
    raw_data = request.data
    
    # 将字节串解码为字符串
    decoded_data = raw_data.decode('utf-8')
    
    # 解析 JSON 数据
    try:
        data = json.loads(decoded_data)
    except json.JSONDecodeError as e:
        print("系统错误：无法解析json数据")
        return oput(2,'系统错误：无法解析json数据')
        # return jsonify({"error": f"Invalid JSON data: {e}"}), 400
    
    # 提取 text 字段
    text = data.get('text')
    
    # 如果 text 为空，则返回错误
    if not text:
        print("系统错误：没有提供任何会议数据")
        return oput(2,'系统错误：没有提供任何会议数据')
        
        # return jsonify({"error": "No text provided"}), 400
    
    
    # 处理并返回数据
    processed_text = process_text(text)
    
    # 1、将录音的文字信息记录到文件
    save_text_to_file(processed_text)
    
    # 根据文件 生成本周及下周内容
    file_path = "本周模板.xlsx"
    text = """
        将文件里面的下周新任务，全部列出，并当做是本周的任务；并根据会议说话的内容，判断任务是否完成；格式要求：任务、执行人、完成情况、预计完成时间（日期格式，例如2024年11月5号）；
        然后再根据会议说话内容，列出下周的任务；格式和上面的相同；
        
        输出的格式要求是json，举例：{
            "this_week_task": [
                {
                    "task": "A",
                    "executor": "XX",
                    "plan_end_time": "2024-08-12",
                    "state": "未完成"
                },
                {
                    "task": "B",
                    "executor": "未明确指定",
                    "plan_end_time": "2024-08-12",
                    "state": "完成"
                },
                {
                    "task": "C",
                    "executor": "未明确指定",
                    "plan_end_time": "2024-08-12",
                    "state": "未完成"
                }
            ],
            "next_week_task": [
                {
                    "task": "D",
                    "executor": "未明确指定",
                    "plan_end_time": "2024-08-19",
                    "state": "-"
                },
                {
                    "task": "E",
                    "executor": "未明确指定",
                    "plan_end_time": "2024-08-19",
                    "state": "-"
                }
            ]
        }

        其他任何文字都不要给我
        
        会议说话的内容为:
    """
    
    final_text = text + processed_text
    
    # 2、将文字信息发送给ai处理
    response_ai = file_send_to_ai(file_path,final_text)

    # 3、将ai回答的内容转为excel文件
    res = response_ai_transfer_to_excel(response_ai)

    email_receivers = ['1104024205@qq.com', 'huangxing.daas@centerm.com']
    
    email_subject = res['friday_date_str'] + "会议总结"
    
    email_body = "您好，附件为本周例会的生成文件，请查收"
    
    email_file = res['file_name']
    send_info_to_email(email_receivers,email_subject,email_body,email_file)
    
    res = {
        'response_ai':response_ai
    }
    
    return oput(1,"请求成功",res)
    # return jsonify({"response_ai":response_ai})


def send_info_to_email(email_receivers,subject,body,attachment_path = None):
    # 发件人和收件人邮箱
    sender = '346025432@qq.com'
    receivers = email_receivers

    # 邮件内容
    subject = subject
    body = body

    # 附件的路径
    attachment_path = attachment_path

    # 创建MIMEMultipart邮件对象
    message = MIMEMultipart()
    message['From'] = sender
    message['To'] = ', '.join(receivers)  # 将收件人列表转换为逗号分隔的字符串
    message['Subject'] = subject

    # 添加邮件正文
    message.attach(MIMEText(body, 'plain', 'utf-8'))

    # 添加附件
    if attachment_path:
        with open(attachment_path, 'rb') as attachment:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(attachment.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment', filename=attachment_path)
        message.attach(part)

    # SMTP服务器信息
    smtp_server = 'smtp.qq.com'
    smtp_port = 587  # 或者使用465端口，取决于是否使用SSL
    smtp_username = sender  # 通常是你的QQ邮箱
    smtp_password = 'fcdsbuerkgnxbiee'

    # 创建SMTP对象并开始TLS加密传输
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()

    # 登录SMTP服务器
    server.login(smtp_username, smtp_password)

    # 发送邮件
    server.sendmail(sender, receivers, message.as_string())

    # 断开服务器连接
    server.quit()

    
    
    


def oput(status,msg,data=None,code=200):
    return jsonify({
        "status":status,
        'msg':msg,
        'data':data
    }),code
    


def friday_date():
   # 获取当前日期
    today = datetime.datetime.now()

    # 计算今天是周几（Monday=0, Sunday=6）
    today_weekday = today.weekday()

    # 计算到本周五的天数
    friday_weekday = 4  # Friday is the 4th day of the week (0-6 index)
    days_to_friday = (friday_weekday - today_weekday) % 7

    # 计算本周五的日期
    friday = today + datetime.timedelta(days=days_to_friday)

    # 格式化日期为 YYYYMMDD 格式
    friday_date_str = friday.strftime('%Y%m%d')
    
    # 打印并返回格式化的日期字符串
    print(friday_date_str)
    return friday_date_str

def response_ai_transfer_to_excel(response_ai):
    # 首先尝试将 response_ai 转换成字典，假设它是 JSON 格式的字符串
    if isinstance(response_ai, str):
        try:
            response_ai = json.loads(response_ai)
        except json.JSONDecodeError as e:
            print(f"### 错误：无法解析 response_ai 为字典: {e}")
            return

    # 确保 response_ai 是字典
    if not isinstance(response_ai, dict):
        print("### 错误：response_ai 不是字典")
        return

    data = response_ai
    
    print("### 系统提示：正在生成 Excel 文件...")
    wb = Workbook()
    wb.LoadFromFile("template.xlsx")

    sheet = wb.Worksheets[0]
    
    # 计算本周一和本周五的日期
    today = datetime.datetime.today()
    weekday = today.weekday()  # 0=Monday, 6=Sunday
    monday = today - datetime.timedelta(days=weekday)
    friday = monday + datetime.timedelta(days=4)

    # 格式化日期
    monday_str = monday.strftime('%m月%d')
    friday_str = friday.strftime('%m月%d')
    all_friday_str = friday.strftime('%Y-%m-%d')
    # 创建会议标题
    meeting_title = f"{monday_str}-{friday_str}例会"

    sheet.Range["B3"].Text = meeting_title
    sheet.Range["B4"].Text = all_friday_str

    
    this_week_template_row = sheet.Rows[7]
    next_week_template_row = sheet.Rows[8]
    first_row_index = 10
    row_index = first_row_index

    # 确保 data 包含 "this_week_task" 和 "next_week_task"
    if "this_week_task" in data:
        for task in data["this_week_task"]:
            sheet.CopyRow(this_week_template_row, sheet, row_index, CopyRangeOptions.All)
            sheet.Range[f"B{row_index}"].Text = f"{task.get('task', '')};--{task.get('state', '')}"
            sheet.Range[f"F{row_index}"].Text = task.get("executor", '')
            sheet.Range[f"G{row_index}"].Text = task.get("plan_end_time", '')
            row_index += 1

    if row_index - 1 > first_row_index:
        sheet.Range[f"A{first_row_index}:A{row_index - 1}"].Merge()

    first_row_index = row_index
    if "next_week_task" in data:
        for task in data["next_week_task"]:
            sheet.CopyRow(next_week_template_row, sheet, row_index, CopyRangeOptions.All)
            sheet.Range[f"B{row_index}"].Text = task.get("task", '')
            sheet.Range[f"F{row_index}"].Text = task.get("executor", '')
            sheet.Range[f"G{row_index}"].Text = task.get("plan_end_time", '')
            row_index += 1
    if row_index - 1 > first_row_index:
        sheet.Range[f"A{first_row_index}:A{row_index - 1}"].Merge()
    sheet.DeleteRow(8, 2)

    friday_date_str = friday_date()

    excel_file_name = f"{friday_date_str}周例会-创新发展部.xlsx"
    
    wb.SaveToFile(excel_file_name)
    
    print("### 系统提示：Excel 生成完毕")
    
    tmp_dict = {
        "friday_date_str":friday_date_str,
        "file_name":excel_file_name,
    }
    
    return tmp_dict
    
    
# 保存内容到文件里，文件夹为今日日期，如果没有则创建，然后创建当前时间戳的文件夹；最后创建文件，文件名为当前时间戳，内容为text
def save_text_to_file(text):
    print("###系统提示：正在将录音文字信息保存为文件...")
    # 获取当前日期
    current_date = datetime.datetime.now().strftime('%Y-%m-%d')  # 修正这里
    # 获取当前时间戳
    timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')

    # 创建以当前日期命名的文件夹
    date_folder_path = os.path.join('data', current_date)
    os.makedirs(date_folder_path, exist_ok=True)

    # 创建以当前时间戳命名的子文件夹
    timestamp_folder_path = os.path.join(date_folder_path, timestamp)
    os.makedirs(timestamp_folder_path, exist_ok=True)

    # 创建文件
    file_path = os.path.join(timestamp_folder_path, timestamp + '.txt')
    with open(file_path, 'w') as file:
        file.write(text)
    print("###系统提示：保存完毕")


# kimi
def text_send_to_ai(text):
    client = OpenAI(
        api_key = "sk-dlwCiNCL54ebpt30BBNe728WBePcBXS9igZDAlwtGYTPIGwi",
        base_url = "https://api.moonshot.cn/v1",
    )
    
    completion = client.chat.completions.create(
        model = "moonshot-v1-8k",
        messages = [
            {"role": "system", "content": "你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。"},
            {"role": "user", "content": text}
        ],
        temperature = 0.3,
    )
    
    print(completion.choices[0].message.content)


def file_send_to_ai(file_path,text):
    print("###系统提示：AI大模型处理中...")
    
    client = OpenAI(
        api_key = "sk-dlwCiNCL54ebpt30BBNe728WBePcBXS9igZDAlwtGYTPIGwi",
        base_url = "https://api.moonshot.cn/v1",
    )
    
    # xlnet.pdf 是一个示例文件, 我们支持 pdf, doc 以及图片等格式, 对于图片和 pdf 文件，提供 ocr 相关能力
    file_object = client.files.create(file=Path(file_path), purpose="file-extract")
    
    # 获取结果
    # file_content = client.files.retrieve_content(file_id=file_object.id)
    # 注意，之前 retrieve_content api 在最新版本标记了 warning, 可以用下面这行代替
    # 如果是旧版本，可以用 retrieve_content
    file_content = client.files.content(file_id=file_object.id).text
    
    # 把它放进请求中
    messages = [
        {
            "role": "system",
            "content": "你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答",
        },
        {
            "role": "system",
            "content": file_content,
        },
        {"role": "user", "content": text},
    ]
    
    # 然后调用 chat-completion, 获取 Kimi 的回答
    completion = client.chat.completions.create(
    model="moonshot-v1-32k",
    messages=messages,
    temperature=0.3,
    )
    
    print(completion.choices[0].message.content)
    print("###系统提示：AI大模型处理完毕")
    return completion.choices[0].message.content
    

def process_text(text):
    
    
    # 假设这里是对文本进行一些处理
    # 这里直接返回原样
    return text

if __name__ == '__main__':
    app.run(debug=True)